<template>
  <div>
    <CategorySelector :disabled="isShowAttrList" style="margin-bottom: 10px"></CategorySelector>
    <el-card>
      <div v-if="isShowAttrList">
        <el-button :disabled="!categoryStore.category3Id" type="primary" :icon="Plus" @click="toSaveAttrValue"
          >添加属性</el-button
        >
        <el-table :data="attrList" border style="width: 100%">
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80"
          />
          <el-table-column prop="attrName" label="属性名称" width="150" />
          <el-table-column prop="address" label="属性值列表">
            <template v-slot="{ row }">
              <el-tag
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin-right: 6px"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template v-slot="{ row, $index }">
              <el-button
                title="修改"
                size="small"
                type="primary"
                :icon="Edit"
                @click="toEditAttr(row,$index)"
              />
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#ccc"
                title="真的要确定删除这条数据吗?"
                @confirm="confirmDeleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    title="删除"
                    type="danger"
                    size="small"
                    :icon="Delete"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-form>
          <el-form-item label="属性名" style="width: 300px">
            <el-input placeholder="请输入属性名" v-model="attrInfo.attrName" />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :disabled="!attrInfo.attrName"
              @click="addAttrValue"
              >添加属性值</el-button
            >
          </el-form-item>
        </el-form>
        <el-table border :data="attrInfo.attrValueList">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          />
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-input
                size="small"
                ref="inputRef"
                v-model="row.valueName"
                v-if="row.isShowInput"
                @blur="deleteCurrentRow(row, $index)"
              ></el-input>
              <span v-else @dblclick="toEditAttrValue(row,$index)">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row,$index}">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#ccc"
                title="真的要确定删除这条数据吗?"
                @confirm="confirmEventAttrValue($index)"
              >
                <template #reference>
                  <el-button
                    title="删除"
                    type="danger"
                    size="small"
                    :icon="Delete"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveAttrInfo" :disabled="!attrInfo.attrValueList.length">保存</el-button>
        <el-button type="default" @click="isShowAttrList = true"
          >取消</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import CategorySelector from "@/components/CategorySelector/index.vue";
export default {
  name: "Attr",
  components: {
    CategorySelector,
  },
};
</script>
<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { InfoFilled } from "@element-plus/icons-vue";
import { useCategoryListStore } from "@/stores/categoryList";
import { reqGetAttrListData, reqDeleteOneAttr, reqAddOrUpdateAttrInfo } from "@/api/product/attr";
import { ElMessage } from "element-plus";
import type {AttrInfoModel,AttrListModel,AttrValueInfoModel} from '@/api/product/model/attrModel'
const isShowAttrList = ref<boolean>(true);

// 定义一个数组来存储书写列表数据
const attrList = ref<AttrListModel>([]);

// 定义一个变量 为对应输入框 以便于获取输入框对象
const inputRef = ref<HTMLInputElement>();

// 定义一个属性对象，用于收集要添加的属性信息
const attrInfo = reactive<AttrInfoModel>({
  attrName: "", // 要存储的属性名
  attrValueList: [], // 存储属性的数组
  categoryLevel: 3, // 等级是三级
  categoryId: -1, // id值
});
// 获取store
const categoryStore = useCategoryListStore();

// 1. 获取属性列表的函数 此函数 增加属性 删除属性 获取属性时都需要重复调用一次
const getAttrListData = async () => {
  attrList.value = await reqGetAttrListData({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number,
  });
 
};

// 2. 监听三级导航id的变化 进而发送请求获取列表数据
watch(
  () => categoryStore.category3Id,
  async (category3Id) => {
    // console.log('cca',category3Id);
    if (!category3Id) {
      // 数组列表要清空
      attrList.value = []; // 根据数组内容清空，不要显示数据列表了
      return; // 如果category3Id为空  不要再发送请求1了
    }
    // 重新获取属性列表
    getAttrListData();
  },
  { immediate: true }
); // 这里开启立即监视,让切换有回来的页面立即渲染

// 3. 删除数据
const confirmDeleteAttr = async (id: number) => {
  await reqDeleteOneAttr(id);
  // 如果删除成功 则要提示用户
  ElMessage.success("删除属性成功");
  // 成功后重新发请求
  getAttrListData();
};
// 4. 添加属性值
const addAttrValue = () => {
  attrInfo.attrValueList.push({
    valueName: "",
    attrId: attrInfo.id, // 编辑的时候使用
    isShowInput: true, // 是不是显示输入框 还是显示span标签
  });
  // 等页面中的内容渲染完毕之后，才执行里面的业务逻辑
  // nextTick的执行时机是在页面最后一次数据更新完成之后执行
  nextTick(() => {
    inputRef.value?.focus();
  });
};
// 5. 失去焦点时 删除当前每页属性值的那一项
const deleteCurrentRow = (row:AttrValueInfoModel, index:number) => {
  //  1. 判断一下当前输入框中有没有值
  if (!row.valueName) {
    // 2. 如果没有值 则删除当前行
    attrInfo.attrValueList.splice(index, 1);
    return;
  }
  // 3. 如果有值 则失去焦点后要显示span标签 而非el-input
  row.isShowInput = false;
};
// 6. 修改属性值
const toEditAttrValue = (row:AttrValueInfoModel, index:number)=>{
  // 1.让输入框显示出来
  row.isShowInput = true
  // 让当前输入框获取焦点
  nextTick(()=>{
    inputRef.value?.focus()
  })
}
// 7. 删除属性
const confirmEventAttrValue = (index:number) => {
  attrInfo.attrValueList.splice(index,1)
}
// 8. 添加新属性的时候 要清空原来的值
const toSaveAttrValue = ()=>{
  // 要显示添加属性的页面
  isShowAttrList.value = false
  // 清空旧的值
  attrInfo.attrName=""
  attrInfo.attrValueList = []
  delete attrInfo.id
}

// 9. 实现属性对象的添加功能
const saveAttrInfo = async()=>{
  attrInfo.categoryId = categoryStore.category3Id

  await reqAddOrUpdateAttrInfo(attrInfo)
  ElMessage.success("属性添加成功")
  // 跳转到列表页
  isShowAttrList.value = true
  // 重新获取数据
  getAttrListData()
}
// 10. 更新属性之数据回显
const toEditAttr = (row:AttrInfoModel)=>{
  isShowAttrList.value = false
  Object.assign(attrInfo,row)
}
</script>


<style>
</style>